package com.webinsky.publish.service.impl;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

import javax.mail.MessagingException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.webinsky.common.utils.EmailUtils;
import com.webinsky.common.utils.EmailUtils.EmailContent;
import com.webinsky.common.utils.EmailUtils.EmailFrom;
import com.webinsky.common.utils.EmailUtils.EmailSent;
import com.webinsky.common.utils.EmailUtils.EmailSmtpServre;
import com.webinsky.publish.domain.EmailSettingInfo;
import com.webinsky.publish.persist.dao.EmailSettingMapper;
import com.webinsky.publish.persist.entity.EmailSetting;
import com.webinsky.publish.service.EmailSettingManagement;

@Service
public class EmailSettingManagementImpl implements EmailSettingManagement {
	// logger
	private static final Logger logger = LoggerFactory.getLogger(EmailSettingManagementImpl.class);
	
	@Autowired
	private EmailSettingMapper emailSettingDao;
	
	private List<String> parseRecievers(String recievers){
		List<String> lReciever = new ArrayList<>();
		String[] strRecievers = recievers.split(";");
		for (String strReciever : strRecievers ) {
			lReciever.add(strReciever);
		}
		return lReciever;
	}

	@Override
	public void createOrUpdate(EmailSettingInfo setting) {
		if ( setting == null ) {
			logger.info("{}createOrUpdate setting is null");
			return;
		}
		EmailSetting emailSetting = null;
		if ( setting.getId() > 0 ) {
			emailSetting = emailSettingDao.selectById(setting.getId());
			if ( emailSetting != null ) {
				if ( setting.getPort() > 0 ) {
					emailSetting.setPort(setting.getPort());
				}
				if ( setting.getRecievers() != null || !setting.getRecievers().isEmpty() ) {
					emailSetting.setRecievers(String.join(";", setting.getRecievers()));
				}
				if ( setting.getSender() != null ) {
					emailSetting.setSender(setting.getSender());
				}
				if ( setting.getSenderPasword() != null ) {
					emailSetting.setPassword(setting.getSenderPasword());
				}
				if ( setting.getSmtp() != null ) {
					emailSetting.setSmtp(setting.getSmtp());
				}
				emailSettingDao.updateByPrimaryKey(emailSetting);
			}
		} else {
			if ( setting.getPort() <= 0 || setting.getRecievers() == null || setting.getSender() == null || setting.getSenderPasword() == null || setting.getSmtp() == null ) {
				return;
			}
			emailSetting = new EmailSetting();
			emailSetting.setPassword(setting.getSenderPasword());
			emailSetting.setPort(setting.getPort());
			emailSetting.setRecievers(String.join(";", setting.getRecievers()));
			emailSetting.setSender(setting.getSender());
			emailSetting.setSiteId(setting.getSiteId());
			emailSetting.setSmtp(setting.getSmtp());
			emailSettingDao.insert(emailSetting);
			setting.setId(emailSetting.getId());
		}
	}

	@Override
	public EmailSettingInfo loadBySiteId(int siteId) {
		if ( siteId <= 0 ) {
			return null;
		}
		List<EmailSetting> settings = emailSettingDao.selectBySiteId(siteId);
		if ( settings.isEmpty() ) {
			return null;
		}
		EmailSettingInfo info = new EmailSettingInfo();
		info.setId(settings.get(0).getId());
		info.setPort(settings.get(0).getPort());
		info.setRecievers(parseRecievers(settings.get(0).getRecievers()));
		info.setSender(settings.get(0).getSender());
		info.setSenderPasword(settings.get(0).getPassword());
		info.setSiteId(settings.get(0).getSiteId());
		info.setSmtp(settings.get(0).getSmtp());
		return info;
	}

	@Override
	public boolean testSendEmail(int siteId) {
		if ( siteId <= 0 ) {
			logger.info("{} testSendEmail siteid = " + siteId + " 邮件信息没有设置");
			return false;
		}
		
		// 发送邮件
		List<EmailSetting> settings = emailSettingDao.selectBySiteId(siteId);
		if ( settings.isEmpty() ) {
			logger.info("{} testSendEmail siteid = " + siteId + " 邮件信息没有设置");	
			return false;
		}
		EmailSetting setting = settings.get(0);
		EmailContent content = new EmailContent();
		EmailFrom from = new EmailFrom();
		from.formName = setting.getSender();
		from.fromEMail = setting.getSender();
		content.from = from;
		EmailSent sent = new EmailSent();
		sent.body = "this is a test";
		sent.recievers = setting.getRecievers().split(";");
		sent.subject = "测试邮件";
		content.sender = sent;
		EmailSmtpServre server = new EmailSmtpServre();
		server.smtpIsSSL = true;
		server.smtpPassword = setting.getPassword();
		server.smtpPort = setting.getPort();
		server.smtpServer = setting.getSmtp();
		server.smtpUserName = setting.getSender();
		content.smtpServer = server;
		
		try {
			EmailUtils.sendMail(content);
			return true;
		} catch (UnsupportedEncodingException e) {
			logger.error("{} submitInfo 发送是失败", e);
		} catch (MessagingException e) {
			logger.error("{} submitInfo 发送是失败", e);
		}
		return false;
	}

}
